package com.yanqu.road.logcollector;


import com.yanqu.road.dao.db.DBTableInfoMgr;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbPoolMgr;
import com.yanqu.road.logcollector.config.ClickHouseConfig;
import com.yanqu.road.logcollector.config.ConfigBeans;
import com.yanqu.road.logcollector.db.ClickHousePool;
import com.yanqu.road.logcollector.log.CKLogMgr;
import com.yanqu.road.logcollector.web.StartController;
import com.yanqu.road.utils.CodeVersion;
import com.yanqu.road.utils.LogUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Collections;


@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ServletComponentScan
public class GameLogCollectorApplication {
    public static void main(String[] args) {
        try {
            CodeVersion.printCodeVersion();
            SpringApplication app = new SpringApplication(GameLogCollectorApplication.class);
            app.setDefaultProperties(Collections.singletonMap("spring.config.location", "classpath:/application.yml"));
            ConfigurableApplicationContext context = app.run(args);
            ConfigBeans.init(context);

            ClickHouseConfig serverConfig = ConfigBeans.getConfigBean(ClickHouseConfig.class);
            // 自动创建表
            DbPoolMgr.getInstance().createPool(new ClickHousePool(serverConfig));

            try {
                DBTableInfoMgr.getInstance().init(DbNameStrategy.getCKLogDb(), "com.yanqu.road.entity.log", true, serverConfig.getDatabase(), serverConfig.getCluster());
            } catch (Exception e) {
                LogUtils.ERROR.info("DBTableInfoMgr init error!", e);
            }

            CKLogMgr.getInstance().setCanSave(true);
            StartController.startSuccess();

            //注册关服
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                CKLogMgr.getInstance().stop();
                LogUtils.OPEN_AND_CLOSE.info("notify process stop success!");
                LogManager.shutdown();
            }, "shutDownHook"));
            LogUtils.OPEN_AND_CLOSE.info("notify process start success!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
